package cn.iocoder.yudao.module.ym.service.ticketlog;

import cn.iocoder.yudao.module.infra.enums.TicketLogRecordConstants;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.ym.controller.admin.ticketlog.vo.*;
import cn.iocoder.yudao.module.ym.dal.dataobject.ticketlog.TicketLogDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.ym.dal.mysql.ticketlog.TicketLogMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserNickname;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.TICKET_LOG_NOT_EXISTS;

/**
 * 工单日志 Service 实现类
 *
 * @author 韩艳阳
 */
@Service
@Validated
public class TicketLogServiceImpl implements TicketLogService {

    @Resource
    private TicketLogMapper ticketLogMapper;

    @Override
    public Long createTicketLog(TicketLogSaveReqVO createReqVO) {
        String content = createReqVO.getContent();
        createReqVO.setContent(String.format(TicketLogRecordConstants.ADD_COMMENT,getLoginUserNickname(),content));
        // 插入
        TicketLogDO ticketLog = BeanUtils.toBean(createReqVO, TicketLogDO.class);
        ticketLogMapper.insert(ticketLog);
        // 返回
        return ticketLog.getId();
    }

    @Override
    public void updateTicketLog(TicketLogSaveReqVO updateReqVO) {
        // 校验存在
        validateTicketLogExists(updateReqVO.getId());
        // 更新
        TicketLogDO updateObj = BeanUtils.toBean(updateReqVO, TicketLogDO.class);
        ticketLogMapper.updateById(updateObj);
    }

    @Override
    public void deleteTicketLog(Long id) {
        // 校验存在
        validateTicketLogExists(id);
        // 删除
        ticketLogMapper.deleteById(id);
    }

    private void validateTicketLogExists(Long id) {
        if (ticketLogMapper.selectById(id) == null) {
            throw exception(TICKET_LOG_NOT_EXISTS);
        }
    }

    @Override
    public TicketLogDO getTicketLog(Long id) {
        return ticketLogMapper.selectById(id);
    }

    @Override
    public PageResult<TicketLogDO> getTicketLogPage(TicketLogPageReqVO pageReqVO) {
        return ticketLogMapper.selectPage(pageReqVO);
    }

}